package com.woniuxy.sale.config;

import com.woniuxy.commons.entity.Dict;
import com.woniuxy.sale.service.DictService;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 把数字字典放到redis里面
 * <P> Date: 2022/4/19:17:49
 * <P> Description:
 */

@Component
public class DictConfig implements ApplicationRunner {


    @Resource
    private DictService dictService;

    public static Map<Long, Dict> dictCache;

    public static  DictService dictService1 ;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.dictCache = dictService.findAllDict();
        dictService1 = dictService;
    }


    /**
     * <P>Author ideaAdmin
     * <P>TODO: 根据父id 返回它的所有子类
     * <P>Date 20:47 2022/4/19
     * <P>* @param id
     * <P>* @return java.util.List<com.woniuxy.commons.entity.Dict>
     **/
    public static List<Dict> getDict(Long id) {
        if (dictCache == null) {
           dictCache = dictService1.findAllDict();
        }
        try {
            return dictCache.entrySet()
                    .stream()
                    .filter(longDictEntry -> {
                        Dict value = longDictEntry.getValue();
                        return value.getParentId().compareTo(id) == 0;
                    })
                    .map(Map.Entry::getValue)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Dict getDictOne(long id,int value){
        if (dictCache == null) {
            dictCache = dictService1.findAllDict();
        }
        try {
            return getDict(id).stream()
                    .filter(dict -> dict.getValue().compareTo((long) value) == 0 )
                    .findFirst()
                    .get();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
